#pragma once

#include <iostream>
#include <string>
#include <sys/stat.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <pthread.h>

void *routine(void *args)
{
    pthread_detach(pthread_self());
    int *sock = static_cast<int *>(args);
    std::string msg;
    while (1)
    {
        std::cout << "Enter# ";
        std::cout<<std::endl;
        std::getline(std::cin, msg);
        write(*sock, msg.c_str(), msg.size());
    }
}

class TcpClient
{
public:
    TcpClient(const std::string &serverip, const uint16_t &port)
        : _serverip(serverip), _port(port), _sock(-1)
    {
    }

    void initClient()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            std::cerr << "socket create error" << std::endl;
            exit(2);
        }
    }

    void start()
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_serverip.c_str());

        if (connect(_sock, (struct sockaddr *)&server, sizeof(server)) != 0)
        {
            std::cerr << "connect error" << std::endl;
        }
        else
        {
            pthread_t tid;
            pthread_create(&tid, nullptr, routine, &_sock);

            while (1)
            {
                char buffer[1024];
                int n = read(_sock, buffer, sizeof(buffer) - 1);
                if (n > 0)
                {
                    buffer[n] = 0;
                    std::cout <<"                                   "<< buffer << std::endl;
                }
                else
                {
                    break;
                }
            }
        }
    }

    ~TcpClient()
    {
        if (_sock >= 0)
        {
            close(_sock);
        }
    }

private:
    int _sock;
    std::string _serverip;
    uint16_t _port;
};
